package me.yuzho.study.concurrency;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.stream.Collectors;
import java.util.stream.IntStream;


public class CallableDemo {

    public static void main(String[] args) {
        ExecutorService exec = Executors.newCachedThreadPool();
        
        List<Future<String>> rets = IntStream.range(0, 10).mapToObj(id -> {
            return exec.submit(new TaskWithResult(id));
        }).collect(Collectors.toList());
        
        while (rets.size() > 0) {

            rets = rets.stream().filter(fs ->{
                if(fs.isDone()) {
                    try {
                        System.out.println(fs.get());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return false;
                }
                return true;
            }).collect(Collectors.toList());
        }
        /*
        while(!rets.stream().map(fs -> {
            
            if(fs.isDone()) {
                try {
                    System.out.println(fs.get());
                    rets.remove(fs);
                } catch (Exception e) {
                    e.printStackTrace();
                    return false;
                }
                return true;
            }
            
            return false;
        }).reduce((r1, r2) -> r1 && r2 ).get()){
            Thread.yield();
        }*/
        
        /*
        .forEach(fs -> {
            try {
                if(fs.isDone()) {
                    System.out.println(fs.get());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });*/
        
        exec.shutdown();

    }

}
